<template>
  <div class="flex flex-col h-full">
    <div class="form rounded-md p-4 bg-sky-600/20">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="form"
        label-width="auto"
        style="width: 80%"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item
              label="开始及结束时间"
              prop="date"
            >
              <el-date-picker
                v-model="form.date"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts"
                size="large"
                value-format="YYYY-MM-DD"
                :disabledDate="disabledDateFn"
                @calendar-change="cakebdarChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="报警人姓名"
              prop="callName"
              size="large"
            >
              <el-input v-model="form.callName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item
              label="警情内容"
              prop="content"
            >
              <el-input
                v-model="form.content"
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="showDept">
            <el-form-item
              label="处警单位"
              prop="deptCode"
            >
              <el-select
                v-model="form.chuJingDanWei"
                placeholder="选择处警单位"
                size="large"
                style="width: 240px"
              >
                <el-option
                  v-for="item in listOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
            type="primary"
            @click="onSubmit(ruleFormRef)"
            :disabled="loading"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="table_container bg-sky-600/20 mt-3 rounded-md w-full flex-1">
      <el-container v-if="Data">
        <el-main>
          <el-table
            :data="Data"
            border
            style="width: 100%"
            :height="height"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ 'text-align': 'center' }"
          >
            <el-table-column
              prop="接警单编号"
              label="接警单编号"
              width="180"
            />
            <el-table-column
              prop="处警单位"
              label="处警单位"
              width="180"
            />
            <el-table-column
              prop="处警员"
              label="接警员"
              width="80"
            />
            <el-table-column
              prop="报警时间"
              label="报警时间"
              width="180"
            />
            <el-table-column
              prop="处警时间"
              label="处警时间"
              width="180"
            />
            <el-table-column
              prop="报警人"
              label="报警人"
              width="80"
            />
            <el-table-column
              prop="报警人电话"
              label="报警人电话"
              width="120"
            />
            <el-table-column
              prop="联系地址"
              label="联系地址"
              width="180"
            />
            <el-table-column
              prop="案由"
              label="案由"
              width="180"
            />
            <el-table-column
              prop="报警内容"
              label="报警内容"
              show-overflow-tooltip
            />
          </el-table>
        </el-main>
        <el-footer>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40, 50]"
            :size="size"
            :disabled="loading"
            :background="true"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-footer>
      </el-container>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import jingqingApi from "@/apis/jingqingApi";
import type { ChujingResultList, ChujingParam } from "@/apis/jingqingApi";
import { cakebdarChange, disabledDateFn, shortcuts } from "./datePicker";
import { ElMessageBox } from "element-plus";
import type { ComponentSize, FormRules, FormInstance } from "element-plus";
import store from "@/utils/store";
import { CacheEnum } from "@/enum/cacheEnum";
import { DeptDic, useGetOptions, type ListOptions } from "../helper";


const ruleFormRef = ref<FormInstance>();
const listOptions = ref<ListOptions[]>([]);
const loading = ref(false);
const showDept = ref(false);
//表单验证
interface RuleForm {
  date: string;
  chuJingDanWei: string;
  callName?: string;
  content?: string;
}

const form = reactive<RuleForm>({
  date: "",
  chuJingDanWei: "",
  callName: "",
  content: "",
});

const rules = reactive<FormRules<RuleForm>>({
  date: [{ required: true, message: "请选择要查询的日期", trigger: "blur" }],
  chuJingDanWei: [
    { required: true, message: "请选择要查询的单位", trigger: "blur" },
  ],
});

//分页
const Data = ref<ChujingResultList[]>();
const total = ref(0);
const currentPage = ref(1);
const size = ref<ComponentSize>("default");
const pageSize = ref(10);

//配置表格自适应
let height = "500px";
function getAutoHeight() {
  let el = document.getElementsByClassName("table_container");
  if (el) {
    nextTick(() => {
      height = el[0].clientHeight - 100 + "px";
    });
  }
}

let param: ChujingParam = {
  startDate: "ready",
  endDate: "0",
  pageSize: 5,
  currentPage: 1,
  chuJingDanWei: '',
};

//需要先判断是否已经有数据显示
const handleSizeChange = async (val: number) => {
  if (param.startDate != "ready") {
    loading.value = true;
    param.pageSize = val;
    await jingqingApi
      .getChujingInfo(param)
      .then((res) => {
        if (res.code === 200) {
          Data.value = res.result.resultList;
        } else {
          ElMessageBox.alert("获取失败:"+ res.message);
        }
      })
      .catch((error) => console.log("axios error " + error));
    loading.value = false;
  }
};

const handleCurrentChange = async (val: number) => {
  loading.value = true;
  param.currentPage = val;
  await jingqingApi
    .getChujingInfo(param)
    .then((res) => {
      if (res.code === 200) {
        Data.value = res.result.resultList;
      } else {
        ElMessageBox.alert("获取失败:"+ res.message);
      }
    })
    .catch((error) => console.log("axios error " + error));
  loading.value = false;
};

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      param = {} as ChujingParam;
      param.startDate = form.date[0];
      param.endDate = form.date[1];
      param.chuJingDanWei = form.chuJingDanWei;
      param.pageSize = pageSize.value;
      param.currentPage = currentPage.value;
      if (form.callName) param.callName = form.callName;
      if (form.content) param.content = form.content;
      await jingqingApi
        .getChujingInfo(param)
        .then((res) => {
          if (res.code === 200) {
            Data.value = res.result.resultList;
            total.value = res.result.totalCount;
          } else {
            ElMessageBox.alert("获取失败:"+ res.message);
          }
        })
        .catch((error) => console.log("axios error " + error));

      loading.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};

onMounted(async () => {
   //动态获取指标下拉菜单列表
  useGetOptions(DeptDic).then((res) => {
    listOptions.value = res;
  });
  //获取表格父节点高度
  getAutoHeight();
   //是否为管理员账号
  if(store.get(CacheEnum.TOKEN_NAME).userInfo.DeptCode == "130800000000"){
    showDept.value = true
  }
});
</script>

<style scoped lang="scss"></style>
